<template>
  <common-card title="今日订单" :value="numberFormat(orderToday)">
    <div ref="lineChartRef" style="width: 100%; height: 100%"></div>
    <template #footer>
      <span>昨日订单量</span>
      <span class="emphasis">{{ moneyFormat(orderLastDay) }}</span>
    </template>
  </common-card>
</template>

<script lang="ts">
import CommonCard from "./CommonCard.vue"
export default {
  name: "TodayOrders",
  components: { CommonCard },
}
</script>
<script lang="ts" setup>
import { ref, onMounted, computed, watch } from "vue"
import * as echarts from "echarts"
import type { EChartsType } from "echarts"
import { useReportDataStore } from "@/stores/reportData"
import useFormat from "@/hooks/useFormat"
const { numberFormat, moneyFormat } = useFormat()

const reportDataStore = useReportDataStore()

// 使用计算属性简化数据代码
// 1.1 今日订单量
const orderToday = computed(() => reportDataStore.reportData.orderToday)
// 1.2 昨日订单量
const orderLastDay = computed(() => reportDataStore.reportData.orderLastDay)
// 1.3 x轴数据
const orderTrend = computed(() => reportDataStore.reportData.orderTrend)
// 1.4 y轴数据
const orderTrendAxis = computed(() => reportDataStore.reportData.orderTrendAxis)

// 定义一个ref关联页面中的dom
const lineChartRef = ref()
let myTodayOrdersChart: EChartsType

const myTodayChart = () => {
  return {
    xAxis: {
      boundaryGap: false, // 两边不留空白
      // x轴数据
      data: orderTrendAxis.value,
    },
    yAxis: {
      show: false, // 不显示y轴及其标线
    },
    series: [
      {
        name: "实时订单数据",
        type: "line",
        // 列表数据
        data: orderTrend.value,
        // 线条光滑
        smooth: true,
        // 区域的样式
        areaStyle: {
          color: "purple",
        },
        // 折线点的样式
        itemStyle: {
          opacity: 0,
        },
        // 线的样式
        lineStyle: {
          opacity: 0,
        },
      },
    ],
    // 图表在坐标中显示的位置
    grid: {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0,
    },
    // 显示提示
    tooltip: {
      trigger: "axis",
      confine: true,
    },
  }
}

// 当页面组件挂载完毕的时候,再使用数据生成图形
onMounted(() => {
  myTodayOrdersChart = echarts.init(lineChartRef.value)
  // myTodayOrdersChart.setOption(myTodayChart())
  // 当浏览器宽度发生变化的时候,图标也要发生变化
  window.addEventListener("resize", () => {
    myTodayOrdersChart && myTodayOrdersChart.resize()
  })
})

// 添加一个监视,因为数据是异步获取
watch(orderToday, () => {
  myTodayOrdersChart.setOption(myTodayChart())
})
</script>

<style></style>
